using System;
using System.Drawing;
using System.IO;

namespace Commonplace.Domain
{
	public class ImageDetailRecord : DetailRecord
	{
		Image _image = null;



		public Image Image { get { return _image; } set { _image = value; OnUpdated(); } }


		public ImageDetailRecord()
		{

		}

        public override DetailControl CreateDetailControl()
        {
            return new ImageDetail(this);
        }

        protected override void OnUpdated()
        {
            if (string.Empty != Filename && null == Image)
            {
                try
                {
                    Image img = new Bitmap(Filename);

                    //if the image is too big, it'll take a huge amount of RAM; let's scale it for thumbnail reasons immediately
                    if (img.Width > 250 && img.Height > 250)
                    {
                        int fixedWidth = 250;
                        int fixedHeight = 250;

                        float imageAspectRatio = (float)img.Height / (float)img.Width;
                        float panelAspectRatio = (float)fixedHeight / (float)fixedWidth;
                        bool useWidth = true;

                        if (img.Height > img.Width)
                        {
                            useWidth = false;
                            if (panelAspectRatio > imageAspectRatio)
                                useWidth = true;
                        }
                        else
                        {
                            if (imageAspectRatio > panelAspectRatio)
                                useWidth = false;
                        }

                        int thumbHeight = 0;
                        int thumbWidth = 0;

                        if (true == useWidth)
                        {
                            thumbWidth = fixedWidth;
                            float aspectRatio = (float)img.Height / (float)img.Width;
                            thumbHeight = (int)(thumbWidth * aspectRatio);
                        }
                        else
                        {
                            thumbHeight = fixedHeight;
                            float aspectRatio = (float)img.Height / (float)img.Width;
                            thumbWidth = (int)(thumbHeight / aspectRatio);
                        }

                        Image thumbnail = new Bitmap(img, new Size(thumbWidth, thumbHeight));
                        img = thumbnail;

                        GC.Collect();
                    }

                    Image = img;


                }
                catch (Exception)
                {
                    throw new ArgumentException("Could not load image");
                }
            }

            base.OnUpdated();
        }


	}
}
